package com.sbp.message.schedule;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.sbp.message.api.entity.Message;
import com.sbp.message.api.entity.MessageStatus;
import com.sbp.message.common.RetryUtils;
import com.sbp.message.send_message.MessageSender;
import com.sbp.message.service.ErrorNotifyServiceImpl;
import com.sbp.message.service.cs.MessageCSImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

public class SendingMessageCheckSchedule implements SimpleJob {
    private final static Logger logger = LoggerFactory.getLogger(SendingMessageCheckSchedule.class);

    @Autowired
    private RetryUtils retryUtils;
    @Autowired
    private MessageCSImpl messageCSImpl;
    @Autowired
    private MessageSender messageSender;
    @Autowired
    private ErrorNotifyServiceImpl errorNotifyServiceImpl;


    public void execute(ShardingContext shardingContext) {
        int shardingItem = shardingContext.getShardingItem();
        int shardingTotalCount = shardingContext.getShardingTotalCount();
        logger.debug(System.currentTimeMillis() + ", 当前分片=" + shardingItem + ", 总分片数=" + shardingTotalCount);

        // 根据当前所处的分片顺序,获取对应的消息数据
        List<Message> list = messageCSImpl.selectShardingListByStatusAndElapseTime(MessageStatus.sending, retryUtils.getMinElapseSeconds(), shardingItem, shardingTotalCount);

        // 读取所有状态为发送中的数据循环
        for (Message message : list) {
            try {
                if (retryUtils.isNeedRetry(message)) {
                    message.setRetry(message.getRetry() + 1);
                    messageSender.sendMessage(message);
                    messageCSImpl.updateById(message);
                }
                else if (retryUtils.isDead(message)) {
                    message.setStatus(MessageStatus.dead.getValue());
                    messageCSImpl.updateById(message);

                    errorNotifyServiceImpl.notify("超过最大重试次数", "超过最大重试次数", message);
                }
            } catch (Exception e) {
                logger.warn("", e);
            }
        }
    }


}
